document.addEventListener('DOMContentLoaded', () => {
    fetch('/api/user.php')
        .then(res => res.json())
        .then(data => {
            if (!data.success) {
                alert(data.message);
                window.location.href = '/login';
                return;
            }

            const { user, history } = data;

            document.getElementById('username').textContent = user.username;
            document.getElementById('last_login_time').textContent = user.last_login_time;
            document.getElementById('last_login_ip').textContent = user.last_login_ip;

            const tbody = document.getElementById('history-table');
            history.forEach(entry => {
                const row = document.createElement('tr');
                row.innerHTML = `<td>${entry.login_time}</td><td>${entry.ip_address}</td>`;
                tbody.appendChild(row);
            });
        });
});


function updateUsername() {
    const newUsername = document.getElementById('new_username').value;
    if (!newUsername) return alert('请输入新用户名');
    fetch('/api/user.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ action: 'update_username', username: newUsername })
    })
    .then(res => res.json())
    .then(data => {
        alert(data.message);
        if (data.success) location.reload();
    });
}

function changePassword() {
    const oldPwd = document.getElementById('old_password').value;
    const newPwd = document.getElementById('new_password').value;
    const confirmPwd = document.getElementById('confirm_password').value;

    if (!oldPwd || !newPwd || newPwd !== confirmPwd) {
        alert('请正确填写所有密码字段');
        return;
    }

    fetch('/api/change_password.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ old_password: oldPwd, new_password: newPwd })
    })
    .then(res => res.json())
    .then(data => {
        alert(data.message);
        if (data.success) window.location.href = '/logout';
    });
}

function logout() {
    fetch('/api/logout.php')
        .then(() => window.location.href = '/login');
}